package com.scalar.chiptrack.adaptor.jsi;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.FTPConnectMode;
import com.enterprisedt.net.ftp.FTPException;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: Apr 27, 2007
 * Time: 4:06:44 PM
 */
public class JSIFtpAdaptor extends JobHandler implements AdaptorConstants
{

    private static final String HOST				= "203.117.64.146";
    private static final int SOURCE_WIP_PORT        = 21;
    public static final String FILE_NAME_JSI_WIP    = "Analogix Inventory Report";
    public static final String FILE_NAME_JSI_SHIP   = "Analogix Receiving and Shipping  Report";
    public static final String ADAPTOR_NAME         = "JSI_FG";
    private String m_wipdir                         = "/2009/Inventory Report/";
    private String m_shipdir                        = "/2009/Shipping & Receiving";

    private String m_dataOutputDir  = null;
    private String m_username       = null;
    private String m_password       = null;
    private Logger m_adaptorLogger  = null;
    private int    m_adaptor_id     = -1;
    /**
     *
     * @throws Exception
     */
    public JSIFtpAdaptor() throws Exception
    {
        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation(VENDOR_NAME_JSI, INVENTORY_TYPE_FINISHED_GOODS);

            m_username = vendorAdaptor.getUserId();
            m_password = vendorAdaptor.getPassWord();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory();

            if (m_dataOutputDir != null)
            {
                if (m_dataOutputDir.endsWith("/") || m_dataOutputDir.endsWith("\\"))
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
            }

            AdaptorUtils.makeAllAdaptorDirs(m_dataOutputDir);
             m_adaptorLogger = AdaptorUtils.getAdaptorLogger(m_dataOutputDir, VENDOR_NAME_JSI);
            AdaptorUtils.setLogger( m_adaptorLogger);
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading JSI Adaptor Username, Password details from database, Exception: " + se);
            throw se;
        }

    }
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception
    {
        new JSIFtpAdaptor().execute();
    }

    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            //Print the header details
            AdaptorUtils.printHeader(VENDOR_NAME_JSI, CONSTANT_ADAPTOR);

            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

            /**
             * Login
             */
            FTPClient ftp = login(HOST, SOURCE_WIP_PORT, m_username, m_password);

            if (ftp != null)
            {
                /**
                 * Log the info into the Log directory
                 */
                log("Successfully logged in to " + HOST);
                System.out.println("Successfully logged in to " + HOST);

                // Download files
                ftp.chdir(m_wipdir);
                log("Remote directory changed to " + m_wipdir );
                System.out.println("Remote directory changed to " + m_wipdir);

                //downloading inventory file
                downloadInventoryFile( ftp );
                // change to root directory.
                /*ftp.chdir("../../");
                System.out.println("Remote directory changed to Root Directory ");
                log("Remote directory changed to Root Directory ");

                //
                ftp.chdir(m_shipdir);
                log( "Remote directory changed to " + m_shipdir );
                System.out.println( "Remote directory changed to " + m_shipdir );
                downloadShipmentFile( ftp );*/

                /**
                 * logout from the site
                 */
                 logout( ftp );
                log("\nSuccessfully logged out from JSI FTP site");
                System.out.println("\nSuccessfully logged out from JSI FTP site");
            }
            else
            {
                log("Unable to login to the JSI FTP site");
                throw new ScalarException("Unable to login to the JSI FTP site");
            }
        }
        catch(Exception e)
        {
            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id);
            System.out.println("Exception while trying to connect and read data from " + HOST +" site: " + e);
            log("Exception while trying to connect and read data from " + HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }

    /**
     *
     * @param ftp
     * @throws Exception
     */
    private void downloadInventoryFile(FTPClient ftp) throws Exception
    {

        String tempDirString    = null;
        String finalDir         = null;

        String[] directoryListing = ftp.dir("", true);

        if ((directoryListing == null) || (directoryListing.length == 0))
        {
            return;
        }

        byte[] buf = null;

        FileOutputStream fileOutputStream = null;
        try
        {
            for (int i = 0; i < directoryListing.length; i++)
            {
                if (tempDirString == null)
                {
                    tempDirString = directoryListing[i].trim();
                    finalDir = tempDirString;
                }
                else
                {

					//System.out.println( "tempDirString	" + tempDirString +"	directoryListing[i].trim()	" + directoryListing[i].trim() );

                    java.util.Date strDate1 = getDateFromString(tempDirString);
                    java.util.Date strDate2 = getDateFromString(directoryListing[i].trim());

					//System.out.println("strDate1	" +strDate1 + "	strDate2	" + strDate2);

                    if (strDate1 != null && strDate2 != null)
                    {
                        if (strDate2.compareTo(strDate1) >= 0)
                        {
                            tempDirString = directoryListing[i];
                        }
                    }
                   finalDir = tempDirString;
                }
            }

			//System.out.println( " finalDir			!" + finalDir )	;
			if (finalDir != null && "d".equalsIgnoreCase( finalDir.substring( 0, 1 ) ) )
			{
			
				finalDir = finalDir.substring(finalDir.trim().lastIndexOf(" ")+ 1, finalDir.length());

				//System.out.println( " finalDir			!" + finalDir )	;
				log("finalDir = " + finalDir);

				ftp.chdir(finalDir + "/");
			}	
            String tempFileName = null;
            try
            {
                String[] fileListings = ftp.dir();
                for (int k = 0; k < fileListings.length; k++)
                {
                    if (fileListings[k].startsWith(FILE_NAME_JSI_WIP))
                    {
                        if (tempFileName == null)
                        {
                            tempFileName = fileListings[k];
                        }
                        else
                        {
                            java.util.Date date1 = ftp.modtime(tempFileName);
                            java.util.Date date2 = ftp.modtime(fileListings[k]);

                            if( date1 != null && date2 != null)
                            {
                                if (date2.compareTo(date1) > 0)
                                {
                                    tempFileName = fileListings[k];
                                }
                            }
                        }
                    }
                }
                if (tempFileName != null)
                {
                    log("\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... ");
                    if ( m_adaptor_id > 0 )
                    {
                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , tempFileName.substring(0, tempFileName.indexOf(".") ), FILE_EXTN_XLS, StringUtils.formatDateToString(ftp.modtime(tempFileName), "MM/dd/yyyy HH:mm:ss" ) ) ;
                    }
                    buf = ftp.get(tempFileName);
                    fileOutputStream = new FileOutputStream(m_dataOutputDir + "/" + tempFileName, false);
                    fileOutputStream.write(buf);
                }
            }
            catch (FTPException fte)
            {

                if (!fte.getMessage().equalsIgnoreCase("No files found"))
                {
                    log("Exception while downloading......... " + fte);
                    fte.printStackTrace();
                    logout(ftp);
                    throw fte;
                }
                else
                {
                    log("No Goods Receipt Files Found in the Directory " + finalDir);
                }
            }
            //ftp.chdir( ".." );
        }
        catch (IOException e)
        {
            throw e;
        }

        finally
        {
            if (fileOutputStream != null)
            {
                try
                {
                    fileOutputStream.close();
                }
                catch (IOException ignore) {
                }
            }
        }
    }

    /**
     *  downloading JSI Shipment file
     * @param ftp
     * @throws Exception
     */
    private void downloadShipmentFile(FTPClient ftp) throws Exception
    {
        String[] directoryListing = ftp.dir("", true);

        if ((directoryListing == null) || (directoryListing.length == 0))
        {
            return;
        }

        byte[] buf = null;

        FileOutputStream fileOutputStream = null;
        try
        {
            String tempFileName = null;
            try
            {
                String[] fileListings = ftp.dir();
                for (int k = 0; k < fileListings.length; k++)
                {
                    if (fileListings[k].indexOf(FILE_NAME_JSI_SHIP) != -1)
                    {
                        if (tempFileName == null)
                        {
                            tempFileName = fileListings[k];
                        }
                        else
                        {
                            java.util.Date date1 = ftp.modtime(tempFileName);
                            java.util.Date date2 = ftp.modtime(fileListings[k]);
                            if (date2.compareTo(date1) > 0)
                            {
                                tempFileName = fileListings[k];
                            }
                        }
                    }
                }
                if (tempFileName != null)
                {
                    log("\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... ");
                    buf = ftp.get(tempFileName);
                    fileOutputStream = new FileOutputStream(m_dataOutputDir + "/" + tempFileName, false);
                    fileOutputStream.write(buf);
                }
            }
            catch (FTPException fte)
            {
            }
        }
        catch (IOException e)
        {
            throw e;
        }

        finally
        {
            if (fileOutputStream != null)
            {
                try
                {
                    fileOutputStream.close();
                }
                catch (IOException ignore) {
                }
            }
        }
    }
    /**
    * Logs into the JSI ftp site
    *
    * @ param host JSI Host Name
    * @ param port JSI  Port
    * @ param login user login
    * @ param password user password
    *
    * @return HTTPConnection connection on which all other requests are sent
    * @throws Exception If there are any problems with login
    */
    private FTPClient login( String host, int port, String m_username, String m_password ) throws Exception
    {
        FTPClient ftp = null;

        try
        {
            ftp = new FTPClient( host, port );
            ftp.login( m_username, m_password );
            ftp.debugResponses( false );
            ftp.setType( FTPTransferType.BINARY );
            ftp.setConnectMode( FTPConnectMode.PASV );
        }
        catch (Exception e)
        {
            log( "Could Not able to connect to the JSI FTP site, Exception : " + e );
            throw new ScalarException( "Could Not able to connect to the JSI FTP site" );
        }

        return ftp;
    }

    /**
     *
     * @param ftp
     * @throws Exception
     */
    private void logout( FTPClient ftp ) throws Exception
    {
        if ( ftp == null )
        {
            return;
        }

        try
        {
            ftp.quit();
        }
        catch (Exception ignore)
        {
            System.out.println( "Exception Occuered While Logging Out From JSI FTP Site" + ignore );
            throw new ScalarException( "Exception Occuered While Logging Out From JSI FTP Site" + ignore );
        }
        ftp = null;
    }

    private Date getDateFromString(String dirString)
    {
        String dateString = null;
        String month;
        String year;
		String day;

        Date dt = null;

        if (dirString == null || dirString.length() == 0)
        {
            System.out.println(" Dir String is null ");
            return new Date();
        }

        try
        {

            dateString = dirString.substring(dirString.lastIndexOf(" ")-12, dirString.lastIndexOf(" ") );
			//System.out.println( "-----------------------------------------------------------------------------------" );
			//System.out.println("Dir String "+ dirString);
			//System.out.println("dateString "+ dateString);
            if( dateString != null && dateString.indexOf(" ") != -1 )
            {
               String[] token = dateString.split(" ");
				if( token != null)
				{
					month = token[0].trim();
					day = token[1].trim();
					if( day == null || day.trim().length() == 0 )
					{
						day = token[2].trim();
					}
					//year  = token[1].trim();
					//dateString = year + month;
					dateString = day + month;

					//System.out.println( "MOnth " + month + "		day	" + day );
				}
            }
			//System.out.println("dateString2 "+ dateString);
            dt = StringUtils.format(dateString, "ddMMM");
			//System.out.println("dt "+ dt);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            dt = new Date();
        }
        log("Date caliculated " + dt);
        return dt;
    }

    /**
     *
     * @param message
     */
    private void log(String message)
    {
        if (message == null) return;

        if (m_adaptorLogger != null)
        {
            synchronized (m_adaptorLogger)
            {
                m_adaptorLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }

}
